﻿using Knife.Core.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Knife.Core.Template
{
    public class BaseTemplateController<T> : BaseController where T : BaseEntity
    {
        public BaseTemplateDB<T> TemplateDB = new BaseTemplateDB<T>();
        public string strWhere = "1=1";
        public string strOrder = "gmt_create desc";
        public virtual ActionResult List()
        {
            Result result = new Result();
            JObject Params = GetParams();
            int pageIndex = Convert.ToInt32(Params.GetValue("pageIndex"));
            int pageSize = Convert.ToInt32(Params.GetValue("pageSize"));
            List<T> list = TemplateDB.SelectPageList("*", strWhere, strOrder, pageIndex, pageSize, new Dictionary<string, object>());
            int total = TemplateDB.SelectCount("1=1", new Dictionary<string, object>());
            result.Add("total", total);
            result.Add("rows", list);
            return result;
        }
        public virtual ActionResult Insert(T Entity)
        {
            Result result = new Result();
            TemplateDB.Insert(Entity);
            return result;
        }
        public virtual ActionResult Update(T Entity)
        {
            Result result = new Result();
            TemplateDB.Update(Entity);
            return result;
        }
        public virtual ActionResult Detail()
        {
            Result result = new Result();
            JObject Params = GetParams();
            string keyguid = Convert.ToString(Params["row_id"]);
            T entity = TemplateDB.SelectOne(keyguid);
            result.Add("obj", entity);
            return result;
        }
        public virtual ActionResult Delete()
        {
            Result result = new Result();
            JObject Params = GetParams();
            string keyguid = Convert.ToString(Params["row_id"]);
            TemplateDB.Delete(keyguid);
            return result;
        }
        public virtual ActionResult BatchDelete()
        {
            Result result = new Result();
            JObject Params = GetParams();
            string row_id_list = Convert.ToString(Params["row_id_list"]);
            foreach (string row_id in row_id_list.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList())
            {
                TemplateDB.Delete(row_id);
            }
            return result;
        }
    }
}
